package com.daocao.hua.util;

import android.Manifest;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import com.afollestad.materialdialogs.MaterialDialog;
import com.daocao.hua.R;
import com.daocao.hua.activity.MainActivityNew;
import com.daocao.hua.constant.Const;
import com.daocao.hua.view.Dialog;

import java.io.File;
import java.lang.ref.WeakReference;

/**
 * Created by xsooy-pc on 18-9-27.
 */

public class AppDownloadManager {
    private final WeakReference<Activity> weakReference;
    private DownloadBroadcastReceiver receiver;
    private DownloadChangeObserver downloadObserver;
    private DownloadManager manager;
    private MaterialDialog materialDialog;
    private long lastDownloadId = 0;
    public static final Uri CONTENT_URI = Uri.parse("content://downloads/my_downloads");
    public String download_url;

    public AppDownloadManager(Activity activity, String download_url) {
        this.download_url = download_url;
        weakReference = new WeakReference<Activity>(activity);

        //注册下载监听
        receiver = new DownloadBroadcastReceiver();
        weakReference.get().registerReceiver(receiver, new IntentFilter(
                DownloadManager.ACTION_DOWNLOAD_COMPLETE));

        showInstallDialog();
    }


    public class DownloadBroadcastReceiver extends BroadcastReceiver {

        public void onReceive(Context context, Intent intent) {


            try {
                if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {

                    long myDwonloadID = intent.getLongExtra(
                            DownloadManager.EXTRA_DOWNLOAD_ID, -1);

                    long refernece = PreferenceUtils.getLong(context, "downloadId", 0);

                    if (refernece == myDwonloadID) {
                        manager = (DownloadManager) context
                                .getSystemService(Context.DOWNLOAD_SERVICE);

//                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) installApp();
//                        else
                        installApp(myDwonloadID);

                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 安装app 6.0以上
     */
    public void installApp(long myDwonloadID) {
        try {


            if (Build.VERSION.SDK_INT >= 24) {//判读版本是否在7.0以上
                File file = queryDownloadedApk(weakReference.get());
                Uri apkUri = FileProvider.getUriForFile(weakReference.get(), "com.daocao.hua.fileprovider", file);
                Intent install = new Intent(Intent.ACTION_VIEW);
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
                install.setDataAndType(apkUri, "application/vnd.android.package-archive");
                weakReference.get().startActivity(install);
            } else {
                if (Build.VERSION.SDK_INT >= 23) {
                    try {
                        Intent install = new Intent(Intent.ACTION_VIEW);
                        File apkFile = queryDownloadedApk(weakReference.get());
                        install.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        weakReference.get().startActivity(install);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        Intent install = new Intent(Intent.ACTION_VIEW);
                        Uri downloadFileUri = manager
                                .getUriForDownloadedFile(myDwonloadID);
                        install.setDataAndType(downloadFileUri,
                                "application/vnd.android.package-archive");
                        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        weakReference.get().startActivity(install);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //通过downLoadId查询下载的apk，解决6.0以后安装的问题
    public static File queryDownloadedApk(Context context) {
        File targetApkFile = null;
        DownloadManager downloader = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        long downloadId = PreferenceUtils.getLong(context, "downloadId", 0);
        if (downloadId != -1) {
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(downloadId);
            query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);
            Cursor cur = downloader.query(query);
            if (cur != null) {
                if (cur.moveToFirst()) {
                    String uriString = cur.getString(cur.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                    if (!TextUtils.isEmpty(uriString)) {
                        targetApkFile = new File(Uri.parse(uriString).getPath());
                    }
                }
                cur.close();
            }
        }
        return targetApkFile;
    }

    private void showInstallDialog() {

        Dialog.showV3DefaultDownloadDialog(weakReference.get(), "提示", "亲爱的用户，因业务调整，借款服务和续借服务已全部迁移至", "取消", "立即下载", new Dialog.DialogDefaultClickListener() {
            @Override
            public void confirm() {
                if (!canDownloadState()) {
                    Dialog.showDefaultDialog(weakReference.get(), weakReference.get().getResources().getString(R.string.tip), "请开启下载服务权限", weakReference.get().getResources().getString(R.string.cancel), "前往开启", true, new Dialog.DialogDefaultClickListener() {
                        @Override
                        public void confirm() {
                            String packageName = "com.android.providers.downloads";
                            Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            intent.setData(Uri.parse("package:" + packageName));
                            weakReference.get().startActivity(intent);
                        }

                        @Override
                        public void cancel() {
                            showInstallDialog();
                        }
                    });
                    return;
                }
                downloadApp();
            }

            @Override
            public void cancel() {

            }
        });


    }


    private boolean canDownloadState() {
        try {
            int state = weakReference.get().getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");

            if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
                return false;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private void downloadApp() {
        //判断是否6.0
        if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) && (ContextCompat.checkSelfPermission(weakReference.get(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
            ActivityCompat.requestPermissions(weakReference.get(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    0);
        } else {
            initDownloadManager();
        }
    }


    /**
     * 初始化下载
     */
    public void initDownloadManager() {
        String url = download_url;
        if (TextUtils.isEmpty(url)) {
            url = PreferenceUtils.getString(weakReference.get(), "download_url", "");
        }
        if (TextUtils.isEmpty(url)) {
            return;
        }

        if (materialDialog == null) {
            materialDialog = new MaterialDialog.Builder(weakReference.get())
                    .title("业务调整")
                    .content("正在下载安装包，请稍候..")
                    .progress(false, 100, true)
                    .cancelable(false)
                    .show();
        }

        try {
            manager = (DownloadManager) weakReference.get().getSystemService(Context.DOWNLOAD_SERVICE);
            Uri uri = Uri.parse(url);
            DownloadManager.Request request = new DownloadManager.Request(uri);

            // 设置下载路径和文件名
            request.setDestinationInExternalFilesDir(weakReference.get(), Environment.DIRECTORY_DOWNLOADS, Const.APP_NAME);
//            request.setDestinationInExternalPublicDir("download", Const.APP_NAME);

            request.setDescription("正在下载安装包，请稍候..");

            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

            request.setMimeType("application/vnd.android.package-archive");

            // 设置为可被媒体扫描器找到
            request.allowScanningByMediaScanner();

            // 设置为可见和可管理
            request.setVisibleInDownloadsUi(true);

            lastDownloadId = manager.enqueue(request);

            // 把当前下载的ID保存起来
            PreferenceUtils.putLong(weakReference.get(), "downloadId", lastDownloadId);

            //采用内容观察者模式实现进度
            downloadObserver = new DownloadChangeObserver(null);
            weakReference.get().getContentResolver().registerContentObserver(CONTENT_URI, true, downloadObserver);

        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        }
    }


    private int p = 10;

    //用于显示下载进度
    private class DownloadChangeObserver extends ContentObserver {

        private DownloadChangeObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange) {
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(lastDownloadId);
            DownloadManager dManager = (DownloadManager) weakReference.get().getSystemService(Context.DOWNLOAD_SERVICE);
            final Cursor cursor = dManager.query(query);
            if (cursor != null && cursor.moveToFirst()) {
                final int totalColumn = cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
                final int currentColumn = cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
                int totalSize = cursor.getInt(totalColumn);
                int currentSize = cursor.getInt(currentColumn);
                float percent = (float) currentSize / (float) totalSize;
                int progress = Math.round(percent * 100);
                p = p + Util.getRandomNum(5, 15);
                if (progress < 80) {
                    if (p > 80) materialDialog.setProgress(80);
                    else
                        materialDialog.setProgress(p);
                } else
                    materialDialog.setProgress(progress);
                if (progress == 100) {
                    materialDialog.setProgress(100);
                    materialDialog.dismiss();
                }
            }
        }


    }
}
